package com.lihh.rocket5.normal;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.consumer.ConsumeFromWhere;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.common.protocol.heartbeat.MessageModel;
import org.apache.rocketmq.remoting.common.RemotingHelper;

import java.io.UnsupportedEncodingException;
import java.util.List;

public class BroadCastConsumer {
  public static void main(String[] args) throws MQClientException {
    // 实例化 消费者实例
    DefaultMQPushConsumer consumer = new DefaultMQPushConsumer("group001");
    // 设置 name server地址
    consumer.setNamesrvAddr("localhost:9876");
    // 设置消费模式（广播模式）
    consumer.setMessageModel(MessageModel.BROADCASTING);
    // 订阅消费主题
    consumer.subscribe("order002", "*");
    // 设置消费偏移量
    consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET);
    
    // 添加订阅模式
    consumer.registerMessageListener(new MessageListenerConcurrently() {
      @Override
      public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        for (MessageExt msg : list) {
          String topic = msg.getTopic();
          String msgId = msg.getMsgId();
          try {
            String message = new String(msg.getBody(), RemotingHelper.DEFAULT_CHARSET);
            System.out.println("topic: " + topic + ", msgId: " + msgId + ", message: " + message);
          } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
          }
        }
        // 消费确认
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
      }
    });
    
    consumer.start();
    while (true) {
    }
  }
}
